<template>
	<div>
		<el-upload ref="uploader" list-type="picture-card" :file-list="imgShowList" :show-file-list="showFileList" :limit="limit" :on-exceed="checkLimit" 
			action :http-request="uploadImage" :auto-upload="true" :multiple="multiple" :on-remove="handleRemove">
			<i class="el-icon-plus"></i>
		</el-upload>
		<div style="color: #F56C6C;">{{errorMessage}}</div>
	</div>
</template>
<script>
	export default {
		name: "upload",
		emits: ['success'],
		props: {
			url: {
				type: String,
				default: ''
			},
			limit: {
				type: Number,
				default: 4
			}
		},
		data() {
			return {
				imgShowList: [],
				errorMessage: '',
				imageList: [],
				multiple: true,
				showFileList: true
			};
		},
		mounted() {
			if(this.limit && this.limit == 1) {
				this.multiple = false
				this.showFileList = false
			}
			if(this.url){
				var urls = this.url.split(',');
				urls.forEach((item, index) => {
					if (item) {
						var image = {
							name: item.substring(item.lastIndexOf("/") + 1),
							url: this.$util.showImage(item),
							surl: item
						}
						this.imgShowList.push(image);
					}
				})
				this.$nextTick(()=>{
					this.imgShowList.forEach(item=>{
						this.imageList.push({id: item.uid, url: item.surl})
					})
				})
			}
		},
		methods: {
			checkLimit(files, fileList) {
				this.errorMessage = '最多选择' + this.limit + '张图片'
			},
			uploadImage(e) {
				if (e.file) {
					let params = {
						file: e.file,
						category: 'image'
					};
					this.$api.fileUpload('/common/uploadFile', params).then(res => {

						this.imageList.push({id: e.uid, url: res.data})

						this.callbackFileUrls()
					})
				}
			},
			handleRemove(file, fileList) {
				let i = 0;
				this.imageList.forEach((item, index) => {
					if(file.uid == item.id){
						i = index
					}
				})
				this.imageList.splice(i, 1);
				
				this.callbackFileUrls()
			},
			callbackFileUrls() {
				let imageUrls = []
				this.imageList.forEach(item => {
					imageUrls.push(item.url)
				})
				
				this.$emit('success', imageUrls.join())
			}
		}
	};
</script>
